//
//  CustomNumbleKeyboardView.m
//  CustomNumbleKeyboard
//
//  Created by wi on 12-3-19.
//  Copyright (c) 2012年 Wi.Inc. All rights reserved.
//

#import "CustomNumbleKeyboardView.h"

#define kButtonSizeWidth ([[UIScreen mainScreen] bounds].size.width - 2*(kButtonBetweenSpace + kButtonLeadingSpace))/3
#define kButtonSizeHeight ([[UIScreen mainScreen] bounds].size.width - 2*(kButtonBetweenSpace + kButtonLeadingSpace))/6
#define kButtonLeadingSpace 25.0f
#define kButtonTopSpace 15.0f
#define kButtonBetweenSpace 5.0f
#define TOTALKEYS 12
#define ANIMATEDURATION 0.3f



@interface CustomNumbleKeyboardView ()

@property(strong, nonatomic) NSMutableArray *buttons;

@end

@implementation CustomNumbleKeyboardView

@synthesize cdelegate = cdelegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.windowLevel = UIWindowLevelStatusBar + 999;//设置level高于Status，低于alert。
        self.buttons = [NSMutableArray array];
        [self setAllSubViews:frame];
        [self creatKeysButton];
       
    }
    return self;
}

-(void)setAllSubViews:(CGRect)frame
{
    CGFloat selfHeight = 4*kButtonSizeHeight + 2*kButtonTopSpace + 3*kButtonBetweenSpace;
    frame.size.height = selfHeight;
    self.frame = frame;
    [self setBackgroundColor:[UIColor grayColor]];
    
    UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:(CGRect){0.0f, 0.0f, frame.size}];
    backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
    UIImage *bgImage = [UIImage imageNamed:@"keyboard_bg"];
    UIImage *resizableImage = [bgImage resizableImageWithCapInsets:UIEdgeInsetsMake(44, 44, 44, 44) resizingMode:UIImageResizingModeStretch];
    backgroundImageView.image = resizableImage;
    [self addSubview:backgroundImageView];
}
-(CGFloat)getKeyboardRealHeight
{
    return self.frame.size.height;
}
//创建键盘按键对象
- (void)creatKeysButton
{
    NSMutableArray* data = [self getRandomNum];
    for (NSString* str in data) {
        NSLog(@"%@",str);
    }

    // add the button
    NSUInteger btnTag = 0;
    for (int x = 0; x < TOTALKEYS; x++)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:(CGRect){kButtonLeadingSpace + x%3*(kButtonSizeWidth + kButtonBetweenSpace), kButtonTopSpace + x/3*(kButtonSizeHeight + kButtonBetweenSpace),
            kButtonSizeWidth, kButtonSizeHeight}];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
        switch (x) {
            case 9:
                btn.tag = 10;
                btnTag = [[data objectAtIndex:9] intValue];
                [btn setTitle:@"删除" forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:@"delete_bg"] forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:@"deleteSelect_bg"] forState:UIControlStateSelected];
                break;
            case 10:
                btn.tag = btnTag;
                [btn setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)btnTag] forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:@"numberButton_bg"] forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:@"numberButtonSelect_bg"] forState:UIControlStateSelected];
                break;
                
            case 11:
                btn.tag = x;
                [btn setTitle:@"完成" forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:@"finish_bg"] forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:@"finishSelect_bg"] forState:UIControlStateSelected];
                break;
                
            default:
                [btn setTag:[[data objectAtIndex:x] intValue]];
                [btn setTitle:[NSString stringWithFormat:@"%i",[[data objectAtIndex:x]intValue]] forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:@"numberButton_bg"] forState:UIControlStateNormal];
                [btn setBackgroundImage:[UIImage imageNamed:@"numberButtonSelect_bg"] forState:UIControlStateSelected];
                break;
        }
        btn.adjustsImageWhenHighlighted = TRUE;
        [btn addTarget:self action:@selector(numbleButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.buttons addObject:btn];
        [self addSubview:btn];
    }
}
//重新排列0-9数字按键的顺序
-(void)resetKeyboardNumberButtons
{
    NSMutableArray *numbers = [self getRandomNum];
    for (UIButton *bt in self.buttons) {
        if (bt.tag < 10) {
            [bt setTag:[[numbers objectAtIndex:bt.tag] intValue]];
            [bt setTitle:[NSString stringWithFormat:@"%i",[[numbers objectAtIndex:bt.tag] intValue]] forState:UIControlStateNormal];
        }
    }
    
}
-(void)showCustomKeyboard
{
    [self resetKeyboardNumberButtons];
    self.hidden = NO;
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    CGFloat keyboardHeight = [self getKeyboardRealHeight];
    self.frame = (CGRect){0, screenBounds.size.height, screenBounds.size.width, keyboardHeight};
    [self makeKeyAndVisible];
    [UIView animateWithDuration:ANIMATEDURATION animations:^{
        CGFloat newY = screenBounds.size.height - keyboardHeight;
        self.frame = (CGRect){0, newY, screenBounds.size.width, keyboardHeight};
    } completion:^(BOOL finished) {
        ;
    }];
}
-(void)dismissCustomKeyboard
{
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    [UIView animateWithDuration:ANIMATEDURATION animations:^{
        self.frame = (CGRect){0, screenBounds.size.height, self.frame.size};
    } completion:^(BOOL finished) {
        self.hidden = YES;
        [self resignKeyWindow];
    }];
}
//按键点击事件
- (void)numbleButtonClicked:(id)sender
{
    UIButton* btn = (UIButton*)sender;
    
    NSInteger number = btn.tag;
    
    // no delegate, print log info
    if (nil == cdelegate)
    {
        NSLog(@"Delegate is nil! button tag [%ld]",(long)number);
        return;
    }
    
    if (number <= 9 && number >= 0) 
    {
        [cdelegate numberKeyBoardInput:number];
        return;
    }
    
    if (10 == number) 
    {
        [cdelegate numberKeyBoardBackspace];
        return;
    }
    
    if (11 == number)
    {
        [cdelegate numberKeyBoardFinish];
        return;
    }
}

//0~9随即排列
-(NSMutableArray*)getRandomNum{
    NSArray* array = [NSArray arrayWithObjects:[NSNumber numberWithInt:0],
                      [NSNumber numberWithInt:1],
                      [NSNumber numberWithInt:2],
                      [NSNumber numberWithInt:3],
                      [NSNumber numberWithInt:4],
                      [NSNumber numberWithInt:5],
                      [NSNumber numberWithInt:6],
                      [NSNumber numberWithInt:7],
                      [NSNumber numberWithInt:8],
                      [NSNumber numberWithInt:9],nil];
    
    
    NSMutableArray* randomArray = [NSMutableArray arrayWithArray:array];
//    NSLog(@"%@", randomArray);
    
    srandom((unsigned int)time(NULL));
    NSInteger count = randomArray.count;
    for (int i = 0; i < count; i++) {
        NSInteger target = random() % count;
        
        //swap
        NSNumber* tmpNumber = [randomArray objectAtIndex:target];
        [randomArray replaceObjectAtIndex:target withObject:[randomArray objectAtIndex:i]];
        [randomArray replaceObjectAtIndex:i withObject:tmpNumber];
    }
//    NSLog(@"%@", randomArray);

    return randomArray;
}


@end
